
/**
 * Module dependencies.
 */

var toRegexp = require('path-to-regexp')
var URL = require('url')

/**
 * Expose `expose`.
 */

/**
 * Rewrite `src` to `dst`.
 *
 * @param {String|RegExp} src
 * @param {String} dst
 * @return {Function}
 * @api public
 */

function rewrite (src, dst) {
  var keys = []; var re; var map

  if (dst) {
    re = toRegexp(src, keys)
    map = toMap(keys)
  } else {
  }

  return function (req, res, next) {
    var orig = req.url
    var m
    if (dst) {
      m = re.exec(orig)
      if (!m) {
        return next()
      }
    }
    req.url = req.originalUrl = (dst || src).replace(/\$(\d+)|(?::(\w+))/g, function (_, n, name) {
      if (name) {
        if (m) return m[map[name].index + 1]
        else return req.params[name]
      } else if (m) {
        return m[n]
      } else {
        return req.params[n]
      }
    })
    if (req.url.indexOf('?') > 0) {
      req.query = URL.parse(req.url, true).query
    }
    if (dst) next()
    else next('route')
  }
}

/**
 * Turn params array into a map for quick lookup.
 *
 * @param {Array} params
 * @return {Object}
 * @api private
 */

function toMap (params) {
  var map = {}

  params.forEach(function (param, i) {
    param.index = i
    map[param.name] = param
  })

  return map
}

const path = require('path')
const proxyMiddleware = require('http-proxy-middleware')
const mockArr = require('./rewrite.js')
const mockUrl = {}
mockArr.forEach(function (item) {
  Object.assign(mockUrl, item)
})
var bodyParser = require('body-parser')

const fs = require('fs')
const express = require('express')

const getMockName = function (name) {
  return function (req, res, next) {
    const method = req.body.method
    const filePath = path.join(__dirname, '../mock/' + name + '/' + method + '.json')
    const filePath2 = path.join(__dirname, '../mock/' + name + '/' + method)

    if (fs.existsSync(filePath)) {
      res.jsonp(JSON.parse(fs.readFileSync(filePath).toString()))
      return
    } else if (fs.existsSync(filePath2)) {
      res.jsonp(JSON.parse(fs.readFileSync(filePath2).toString()))
      return
    }
    next()
  }
}

module.exports = function (app) {
  app.use(bodyParser.json())
  app.use(bodyParser.urlencoded({
    extended: true
  }))

  app.use('/benefit/api/v1/gateway.do', getMockName('gateway.do'))
  app.use('/api/ipay/gateway.do', getMockName('gateway.do'))
  app.use('/api/gateway.do', getMockName('gateway.do'))
  app.use('/service/ipay/apigateway.do', getMockName('apigateway.do'))

  Object.keys(mockUrl).forEach(function (url) {
    var mock = mockUrl[url]

    if (/^http:/.test(mock)) {
      var options = {
        target: mock.replace(/(http:\/\/[^/]+)\/.+/, '$1'),
        changeOrigin: true,
        pathRewrite: {}
      }
      options.pathRewrite[url] = mock.replace(/http:\/\/[^/]+\//, '/')
      app.use(proxyMiddleware(options.filter || url, options))
    } else {
      var filepath = path.join(__dirname, '../mock' + mock)
      if (fs.existsSync(filepath)) {
        app.use(url, function (req, res, next) {
          res.jsonp(JSON.parse(fs.readFileSync(filepath).toString()))
        })
      } else {
        app.use(rewrite(url, mock))
      }
    }
  })

  app.use(express.static('mock'))
  // 路由转发
  // app.use(function (req,res,next) {
  //   if(/^\/([^/]+)\.html/.test(req.url)){
  //     if(RegExp.$1!=='md5'&&RegExp.$1!=='test'){
  //       req.url = req.originalUrl = '/test.html';
  //     }
  //   }
  //   next()
  // })
}
